<?php
/**
 * Created by PhpStorm.
 * User: zc
 * Date: 2019/8/5
 * Time: 23:36
 */
namespace app\api\controller\v1;
use addons\adszone\library\Adszone;
use addons\epay\library\Service;
use app\admin\controller\Zlog;
use app\common\controller\Api;
use app\common\library\EvaluationManager;
use app\common\logic\EvaluationM;

use app\common\validate\EvalutationValidate;
use Exception;
use fast\Random;
use think\Db;

class Evaluation extends Api
{
    protected $noNeedLogin = ['notify','index','getBanner','detail'];  //不能登陆方法
    protected $noNeedRight = '*';
    /**
     * 获取测评列表接口
     */
    public function index()
    {
        $page = $this->request->post('page');
        $pagesize = $this->request->post('pagesize');
        $model = new EvaluationM();
        $data = $model->setPage($page)->setPagesize($pagesize)->getList();
        if($data){
            $this->success('', $data);
        }else{
            $this->error('暂无数据');
        }
    }
    public function getBanner() {
        //获取首页轮播图
        $pic = new Adszone('ceping_banner');
        $list = $pic->getAdsByMark('ceping_banner',ORG_CATE_ID);
        $this->success('轮播图', $list);
    }

    /**
     * 获取详情
     */
    public function detail()
    {
        $id = $this->request->post('id');
        $model = new EvaluationM();
        $data = $model->setUserId(UID)->setId($id)->getDetail();

        if($data){
            //判断该课程是否购买
            $this->success('', $data);
        }else{
            $this->error('暂无数据');
        }
    }

    /*
     * 生成支付订单
     * */
    public function add() {
//        $e = new EvaluationManager();
//        (new EvalutationValidate())->goCheck('add');
//        $data = [
//            'name' => input('name', ''),
//            'sex' => input('sex/d'),
//            'birthday'=> input('birthday'),
//            'height' => input('height'),
//            'weight' => input('weight')
//        ];

        $evalutation_id = input('evalutation_id/d', 0);
        if (!$evalutation_id){
            $this->error('未传递测评id');
        }
//        $model = new EvaluationM();
//        $is_buy = $model->setUserId(UID)->setId($evalutation_id)->get_is_buy();
//        if ($is_buy == 1) {
//            $this->error('不能重复购买');
//        }
//        $res = $e->addChildren($data);
        $evalutation = Db::name('evaluation')->find($evalutation_id);
//        $out_trade_no = MD5(time().UID.Random::alnum(4));
        $out_trade_no = date('YmdHis').'20'.Random::alnum(10);

//        $data['mobile'] = input('mobile', '');
        $data['evalutation_id'] = $evalutation_id;
        $data['price'] = $evalutation['price'];
        $data['scalar_id'] = $evalutation['scalar_id'];
        $data['createtime'] = time();
        $data['order_sn'] = $out_trade_no;
//        $data['openid'] = $res['openid'];
        $data['user_id'] = UID;
        $data['org_cate_id'] = ORG_CATE_ID;

        Db::name('evaluation_order')->insert($data);

        $openid = Db::name('third')->where('id', UID)->value('openid');
        //吊起微信支付
        $params = [
            'type'         => 'wechat',
            'orderid' => $out_trade_no,
            'title'        => '购买测评',
            'amount'       => $evalutation['price'],
            'method'       => 'miniapp',
            'openid'       => $openid,
            'auth_code'    => '',
            'notifyurl'    => request()->root(true) . '/api/v1.evaluation/notify',
            'returnurl'    => '',
        ];

        $res = Service::submitOrder($params);
        $this->success('提交成功', $res);

    }


    /*
     * 测评
     * */
    public function notify() {
        $pay = \addons\epay\library\Service::checkNotify('wechat');

        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $out_trade_no = $data['out_trade_no'];;
            //你可以在此编写订单逻辑['order_sn' => $out_trade_no]
            $order = Db::name('evaluation_order')->where(['order_sn' => $out_trade_no])->find();
            if ($order && $order['type'] == 1) {
                echo $pay->success();
                return;
            }

            Db::name('evaluation_order')->where(['order_sn' => $out_trade_no])->setField('type', 1);
            Db::name('evaluation')->where(['id' => $order['evalutation_id']])->setInc('buy_numbers', 1);
        } catch (Exception $e) {
            echo $e->getMessage();
            return;
        }
        echo $pay->success();
    }

    public function getInfo()
    {
        $id = input('eorder_id/d', 0); //evaluation_order表id
        if (!$id) {
            $this->error('未传递测评订单id');
        }
        $info = Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->find();
        if (empty($info)) {
            $this->error('您还未购买该测评');
        }
        $tag = Db::name('evaluation')->where(['id' => $info['evalutation_id']])->value('tag');
        if($tag == '父母问卷'){
            $info['is_parent'] = 2;
        }else{
            $info['is_parent'] = 1;
        }
        $this->success('测评信息！',$info );
    }

    public function doEvaluation()
    {
        $e = new EvaluationManager();
        $is_parent =  input('is_parent');
        if (!in_array($is_parent, [1,2])) {
            $this->error('未传递是否家长测评字段！');
        }
        if($is_parent == 1){
            (new EvalutationValidate())->goCheck('add');
            $data = [
                'name' => input('name', ''),
                'sex' => input('sex/d'),
                'birthday'=> input('birthday'),
                'height' => input('height'),
                'weight' => input('weight'),
            ];
        }else{
            (new EvalutationValidate())->goCheck('adduser');
            $data = [
                'name' => input('name', ''),
                'sex' => input('sex/d'),
                'birthday'=> input('birthday'),
                'role'=>input('role')
            ];
        }
        $id = input('eorder_id/d', 0); //evaluation_order表id
        if (!$id) {
            $this->error('未传递测评订单id');
        }
//        $model = (new EvaluationM())->setUserId(UID)->setId($id);
        $is_buy = Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->find();
        if (empty($is_buy)) {
            $this->error('您还未购买该测评');
        }
        $data['mobile'] = input('mobile', '');
        $data['birthday'] =strtotime($data['birthday']);
        $res = Db::name('evaluation_order')->where(['id' => $id])->update($data);
        if($res){
            $this->success('信息完善成功！' );
        }else{
            $this->error('信息完善失败！' );
        }
    }
    /**
     * 创建测评
     */
    public function createLine() {

        $e = new EvaluationManager();
        $is_parent =  input('is_parent');
        if (!in_array($is_parent, [1,2])) {
            $this->error('未传递是否家长测评字段！');
        }
        $id = input('eorder_id/d', 0); //evaluation_order表id
        if (!$id) {
            $this->error('未传递测评订单id');
        }
        $info = Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->find();
        if (empty($info)) {
            $this->error('您还未购买该测评');
        }

//        $data['mobile'] = input('mobile', '');
        Db::startTrans();
        try{
            if($is_parent == 1){
                $data = [
                    'name' => $info['name'],
                    'sex' =>$info['sex'],
                    'birthday'=> date('Y-m-d',$info['birthday']),
                    'height' =>$info['height'],
                    'weight' => $info['weight']
                ];
                $res = $e->addChildren($data);
                if(isset($res['status_code']) &&  ($res['status_code'] == 401 || $res['status_code'] == 422)){
                    $this->error($res['message']);
                }
            }else{
                $data = [
                    'name' => $info['name'],
                    'sex' =>$info['sex'],
                    'birthday'=> date('Y-m-d',$info['birthday']),
                    'role' =>$info['role']
                ];
                $res = $e->addUsers($data);
                if(isset($res['status_code']) && ($res['status_code'] == 401 || $res['status_code'] == 422)){
                    $this->error($res['message']);
                }
            }
            Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->update(['openid'=>$res['openid']]);
            $info['openid'] = $res['openid'];
            $number = $info['line_number'];
            $e = new EvaluationManager();
            if(!$info['line_number']) {
                $ret = $e->create($info, $is_parent);
                if(isset($ret['status_code']) &&  ($ret['status_code'] == 401 || $ret['status_code'] == 403 || $ret['status_code'] == 422)){
                    $this->error($ret['message']);
                }
                $number = $ret['number'];
                Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->update(['line_number'=>$number]);
//                (new EvaluationM)->setNumber($number);
            }
            if (!$number) {
                $this->error('获取测评订单号失败');
            }else{
                $url = 'https://jigou.jingyunzhixin.com/question1/#/question?number=' . $number;
                $this->success('',$url );
            }
            Db::commit();
        }catch (\think\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        //获取到了订单号 获取测评详情
//        $res = $e->detail($order['order_sn']);
//
//        if (!$res) {
//            $this->error('获取详情失败');
//        }
//
//        if ($res['status'] == 4) {
//            $this->error('已完成测评，正在生成报告');
//        }
//
//        $this->success('测评', $res);

    }

    /**
     * 测评结果
     */
    public function getresult()
    {
        $e = new EvaluationManager();
//        $id = input('id/d', 0); //evaluation表id
//        if (!$id) {
//            $this->error('未传递测评id');
//        }
//        $model = (new EvaluationM())->setUserId(UID)->setId($id);
////        $model = (new EvaluationM())->setUserId(35)->setId($id);
//        $is_buy = $model->get_is_buy();
//        if ($is_buy != 1) {
//            $this->error('您还未购买该测评');
//        }
        $id = input('eorder_id/d', 0); //evaluation_order表id
        if (!$id) {
            $this->error('未传递测评订单id');
        }
        $info = Db::name('evaluation_order')->where(['id' => $id,'type'=>1])->find();
        if (empty($info)) {
            $this->error('您还未购买该测评');
        }
//        $order = $model->getOrder();
        //获取到了订单号 获取测评详情
        $res = $e->detail($info['order_sn']);
        if (!$res) {
            $this->error('获取详情失败');
        }
        Db::name('evaluation_order')->where([
            'id' => $id,
            'type' => 1
        ])->update(['process_type'=>$res['status']]);
        $this->success('测评', $res);
    }

}